from django.contrib import auth
from django.shortcuts import render, HttpResponse, redirect
from aaplication.utils.validCode import get_valid_code_img
from django.http import JsonResponse
from aaplication.MyForms import UserForm
from aaplication.models import UserInfo


def index(request):
    return render(request, 'index.html')


def logout(request):
    auth.logout(request)  # request.session.flush
    return redirect('/login')


def login(request):
    if request.method == 'POST':
        response = {'user': None, 'msg': None}
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        valid_code = request.POST.get('valid_code')

        valid_code_str = request.session.get('valid_code_str')
        if valid_code.upper() == valid_code_str.upper():
            user = auth.authenticate(username=user, password=pwd)
            if user:
                auth.login(request, user)
                response['user'] = user.username
            else:
                response['msg'] = '账号或密码错误'

        else:
            response['msg'] = '验证码错误'
        return JsonResponse(response)

    return render(request, 'login.html')


def get_validCode_img(request):
    data = get_valid_code_img(request)

    return HttpResponse(data)


def register(request):
    if request.is_ajax():
        form = UserForm(request.POST)

        response = {'user': None, 'msg': None}
        if form.is_valid():
            response['user'] = form.cleaned_data.get('user')

            user = form.cleaned_data.get('user')
            pwd = form.cleaned_data.get('pwd')
            email = form.cleaned_data.get('email')
            avatar_obj = request.FILES.get('avatar')

            extra = {}
            if avatar_obj:
                extra['avatar'] = avatar_obj
            UserInfo.objects.create_user(username=user, password=pwd, email=email, **extra)

        else:

            response['msg'] = form.errors

        return JsonResponse(response)

    form1 = UserForm()
    return render(request, 'register.html', {'form2': form1})
